const fs = require("fs")
const path = require("path")
const {exec} = require('child_process')

exports.readEach= function(cDir = __dirname,type='all'){  //返回目录下的目录或所有
    var files = fs.readdirSync(cDir)  //在当前目录下遍历所有文件
    var _return= []
    files.forEach(function (file) {
        var filePath = path.resolve(cDir, "./" + file)
        var stats = fs.statSync(filePath)
        switch(type){
            case 'dir':
                if (stats.isDirectory()){
                    _return.push(file)
                }
                break;
            case 'all':
                _return.push(file)
                break;
        }
    })
    return _return
}

exports.requireModules = function (cDir = __dirname, curentFile = 'index.js') {  //加载指定目录下的所有js文件
    var exports_ = {}
    var files = fs.readdirSync(cDir)  //在当前目录下遍历所有文件
    console.log('all files:', files)
    files.forEach(function (file) {
        var filePath = path.resolve(cDir, "./" + file)
        var stats = fs.statSync(filePath)
        if (stats.isDirectory()) {  //取目录下的index.js文件作为引入文件
            let subFile = path.resolve(filePath, './index.js')
            if (fs.statSync(subFile).isFile()) {
                exports_[file] = require(subFile)
            }
        }
        if (/.js$/.test(file) && curentFile != file) {  //引入js文件
            let docAt = file.lastIndexOf('.js')
            let modlueName = file.substring(0, docAt)
            exports_[modlueName] = require(filePath)
        }
    });
    return exports_
}

exports.execute = function (cmd,options) {  //封装执行shell命令方法
    return new Promise((resolve,reject)=>{
        exec(cmd, options, function (error, stdout, stderr) {
            if (error) {
                console.error(error);
                reject(error)
            }
            else {
                resolve()
                console.log("stdout:",stdout);
                console.log("stderr:",stderr);
            }
        });
    })
}

exports.consoleInfo= function (req,text){  //日志输出
    console.log(req.headers)
    console.log(text)
}

exports.joinRootDir= function(p=''){  //项目根目录作为起始路径
    return path.resolve(process.cwd(), p)
}

exports.getCookie= function(cookie,name){  // 获取指定名称的cookie
    var strcookie = cookie
    if(!strcookie) return ''
    var arrcookie = strcookie.split("; ")  //分割
    for(let i = 0; i < arrcookie.length; i++) {  //遍历匹配
        var arr = arrcookie[i].split("=");
        if (arr[0] == name){
            return arr[1];
        }
    }
    return '';
}